package com.yuan.base.framework;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * ListAdapter基类
 * @param <T>
 * @param <H>
 */
public abstract class BaseViewHolderAdapter<T, H> extends BaseAdapter {


	private LayoutInflater inflater;
	private List<T> items = new ArrayList<>();


	public BaseViewHolderAdapter(Context context) {
		this.inflater = LayoutInflater.from(context);
	}

	public void setData(List<T> item) {
		if (item == null)
			return;
		this.items = item;
	}

	public void addData(T item) {
		if (item == null)
			return;
		this.items.add(item);
	}

	public void addNull() {
		this.items.add(null);
	}

	public void addListData(List items) {
		if (items == null || items.size() == 0)
			return;
		this.items.addAll(items);
	}

	public void addListData(int index, List items) {
		if (items == null || items.size() == 0)
			return;
		this.items.addAll(index, items);
	}

	public List<T> getListData() {
		return this.items;
	}

	public void clearListData() {
		this.items = new ArrayList<>();
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final T item = getItem(position);
		final H holder;
		if (convertView == null) {
			holder = getHolder();
			convertView = getConvertView(item, inflater, position, parent);
			bindViews(convertView, holder, item);
			convertView.setTag(holder);
		} else {
			holder = (H) convertView.getTag();
		}
		refreshView(position, item, convertView, holder);
		return convertView;
	}

	/**
	 * holder.xx=(xx) convertView.findViewById(R.id.xx);
	 * @param item 根据不同item类型初始化不同控件
	 */
	protected abstract void bindViews(View convertView, H holder, T item);

	/**
	 * 初始化布局View
	 * @param item 根据不同item类型初始化不同布局View
	 */
	protected abstract View getConvertView(T item, LayoutInflater inflater, int position, ViewGroup parent);

	/**
	 * @return new ViewHolder
	 */
	protected abstract H getHolder();

	/**
	 * 刷新ui
	 */
	protected abstract void refreshView(int position, T item, View convertView, H holder);

	@Override
	public int getCount() {
		return items.size();
	}

	@Override
	public T getItem(int position) {
		return items.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	protected String getUnNullString(String s, String defalt) {
		return TextUtils.isEmpty(s) ? defalt : s;
	}

	protected String getUnNullString(String s) {
		return TextUtils.isEmpty(s) ? "" : s;
	}


}
